package com.subdoc.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 基类过滤器
 *
 * @className: AbstractFilter
 * @Description: TODO(基类过滤器)
 * @author: Baron
 * @date: 2017/5/19 16:47
 * @version: 1.0
 * @url: https://www.baron.cn
 */
public abstract class AbstractFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
        String menthod = request.getMethod();

        String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());

//        if ("POST".equalsIgnoreCase(menthod)) {
//            // 防止流读取一次后就没有了, 所以需要将流继续写出去
//            ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
//            doFilter((HttpServletRequest)requestWrapper, response, chain, session, menthod, url);
//        }

        doFilter(request, response, chain, session, menthod, url);
    }

    /**
     *
     * @param request
     *            request
     * @param response
     *            response
     * @param session
     *            session 可能为空
     * @param menthod
     *            menthod
     * @param url
     *            url
     */
    public abstract void doFilter(HttpServletRequest request,
                                  HttpServletResponse response, FilterChain chain,
                                  HttpSession session, String menthod, String url)
            throws IOException, ServletException;
}
